package edu.wong.pro.serviceImpl;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.servlet.http.HttpSession;
import javax.swing.filechooser.FileNameExtensionFilter;

import org.apache.struts2.ServletActionContext;
import org.hibernate.Session;
import org.hibernate.Transaction;

import edu.wong.pro.dao.MemberDAO;
import edu.wong.pro.iservice.IOther;
import edu.wong.pro.model.Member;

public class OtherService implements IOther{

	//保存头像
	@Override
	public void loadPhoto(File file) {
		// TODO Auto-generated method stub
		// 取到服务器上传文件存放的路径
	    String path = ServletActionContext.getServletContext().getRealPath(
	                "/photo/");
	    // 取到上传文件的完整路径
	    HttpSession httpSession = ServletActionContext.getRequest().getSession();
	    int  filename = (Integer)httpSession.getAttribute("memberID");
	    //保存数据到图片路径到数据库
	    savePhoto(filename);
	    String FilePath = path + File.separator +filename+".jpg";
	    System.out.println(FilePath);
	    InputStream is = null;
	    OutputStream os = null;
	    try {
	        is=new FileInputStream(file);
	        os=new FileOutputStream(FilePath);
	        byte[] b=new byte[1024];
	        int len=0;
	        while((len=is.read(b))!=-1){
	            os.write(b,0,len);
	            os.flush();
	        }
	        is.close();
	        os.close();
	    } catch (FileNotFoundException e) {
	        e.printStackTrace();
	    } catch (IOException e) {
	        e.printStackTrace();
	    }
	}

	private void  savePhoto(int memId){
		MemberDAO dao = new MemberDAO();
		Member member = dao.findById(memId);
		Session session = dao.getSession();
		Transaction transaction = session.beginTransaction();
		member.setPhoto("photo/"+memId+".jpg");
		dao.attachClean(member);;
		transaction.commit();
		session.close();
	}
	
}
